<?php

class UserStat extends ActiveRecordBase
{
	public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

	public function tableName() {
		return "{{user_stats}}";
	}

	public function relations() {
		return array(
			'user' => array(self::BELONGS_TO, 'User', 'user_id'),
		);
	}
	
	public static function availableStats() {
		return array('like', 'comment', 'quotation', 'point', 'buy', 'gift', 'rent', 'badge');
	}
	
	public static function isValidStat($stat) {
		return in_array($stat, self::availableStats());
	}
	
	public static function addUserStat($user_id = null) {
		
		if ( empty($user_id) ) $user_id = user()->id;
		
		$user_stat = UserStat::model()->findByAttributes(array(
			'user_id' => $user_id,
		));
		
		if ( empty($user_stat) ) {
			$user_stat = new UserStat;
			$user_stat->user_id = $user_id;
			$user_stat->save();
		}
		
	}
	
	public static function increaseStat($stat, $user_id = null) {
		
		if ( empty($user_id) ) $user_id = user()->id;
		
		$field = sprintf('stat_%s', $stat);
		
		if ( self::isValidStat($stat) ) {

			self::addUserStat($user_id);
			
			$command = app()->db->createCommand(sprintf('UPDATE {{user_stats}} SET %1$s=%1$s+1 WHERE user_id=:user_id', $field));
			$command->execute(array(
				':user_id' => $user_id,
			));

		}
		
	}
	
	public static function decreaseStat($stat, $user_id = null) {

		if ( empty($user_id) ) $user_id = user()->id;
		
		$field = sprintf('stat_%s', $stat);
		
		if ( self::isValidStat($stat) ) {
			
			self::addUserStat($user_id);

			$command = app()->db->createCommand(sprintf('UPDATE {{user_stats}} SET %1$s=IF(%1$s-1 >= 0, %1$s-1, 0) WHERE user_id=:user_id', $field));
			$command->execute(array(
				':user_id' => $user_id,
			));

		}

	}
	
	public static function setStat($stat, $value, $user_id = null) {

		if ( empty($user_id) ) $user_id = user()->id;

		$field = sprintf('stat_%s', $stat);

		if ( self::isValidStat($stat) ) {
			
			self::addUserStat($user_id);

			$command = app()->db->createCommand(sprintf('UPDATE {{user_stats}} SET %1$s=:value WHERE user_id=:user_id', $field));
			$command->execute(array(
				':value' => (int) $value,
				':user_id' => $user_id,
			));

		}

	}

}